package com.yanqu.road.dataHelper.repair.logic;

import com.yanqu.road.dataHelper.gameServer.GameServer;
import com.yanqu.road.dataHelper.repair.BaseRepair;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wpj
 * @Date 2020/9/7
 */
public class ChildSpeedRankRepairTask extends BaseRepair {

    public ChildSpeedRankRepairTask(GameServer gameServer) {
        super(gameServer);
    }

    @Override
    public void repair(long param1, String param2) {

        int conditionId = 1000101;
        int activityId = 9001943;
        int alTime = 1599235200;

        // 修改时间以及活动id
        if (getGameServer().getServerInfo().getServerId() >= 10100014) {
            activityId = 9001944;
            alTime = 1599321600;
        }

        for (Map.Entry<Long, BigInteger> entry : getData(alTime).entrySet()) {
            long userId = entry.getKey();
            UserActivityConditionData userActivityConditionData = getUserActivityCondition(activityId, userId, conditionId);
            if (userActivityConditionData != null) {
                BigInteger oldValue = userActivityConditionData.getValue();
                userActivityConditionData.setValue(userActivityConditionData.getValue().add(entry.getValue()));
                getLogger().error("sid:{} uid:{} old:{} new:{} d{}", getGameServer().getServerInfo().getServerId(), userId, oldValue.toString(), userActivityConditionData.getValue().toString(), entry.getValue().toString());
                updateUserActivityConditionData(userActivityConditionData);
            }
        }
    }


    public Map<Long, BigInteger> getData(long time) {
        Map<Long, BigInteger> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = getGameServer().getConnection().prepareCall("select t1.userId as userId, sum(t1.speed+0) as allSpeed from (select userId as userId, childUid as childUid,substring(childUid, -2) as tail, childEarnSpeed as speed  from t_u_marriage where isTwins = 1 and childAdultTime >= ?)t1 where t1.tail != '-2' GROUP BY t1.userId");
            call.setLong(1, time);
            rs = call.executeQuery();
            while (rs.next()) {
                long userId = rs.getLong("userId");
                BigInteger speed = new BigInteger(rs.getString("allSpeed"));
                getLogger().error("{}， {}", userId, speed.toString());
                map.put(userId, speed);
            }
        } catch (SQLException e) {
            getGameServer().getLogger().error("异常错误", e);
        } finally {
            getGameServer().closeConnection(call, rs);
            return map;
        }
    }

    public UserActivityConditionData getUserActivityCondition(int activityId, long userId, int conditionId) {
        Map<Long, BigInteger> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = getGameServer().getConnection().prepareCall("select * from t_u_activity_condition where activityId=? and userId=? and type=42 and conditionId=?");
            call.setInt(1, activityId);
            call.setLong(2, userId);
            call.setInt(3, conditionId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = new UserActivityConditionData();
                data.setUserId(rs.getLong("userId"));
                data.setActivityId(rs.getInt("activityId"));
                data.setConditionId(rs.getInt("conditionId"));

                String value = rs.getString("value");
                if(!StringUtils.isNullOrEmpty(value)) {
                    data.setValue(new BigInteger(value));
                }
                return data;
            }
        } catch (SQLException e) {
            getGameServer().getLogger().error("异常错误", e);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return null;
    }


    private boolean updateUserActivityConditionData(UserActivityConditionData userActivityConditionData){
        boolean result = false;
        String sql = "update t_u_activity_condition set value=? where userId=? and activityId=? and conditionId=?";
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = getConnection().prepareCall(sql);
            int i = 1;
            call.setString(i++, userActivityConditionData.getValue().toString());
            call.setLong(i++, userActivityConditionData.getUserId());
            call.setInt(i++, userActivityConditionData.getActivityId());
            call.setInt(i++, userActivityConditionData.getConditionId());
            result = call.executeUpdate() > 0;
        } catch (Exception e) {
            getLogger().error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return result;
    }

}
